var appPath = getAppPath();
$(function(){
	initJspCompont();
	initJspGrid();
});

function initJspCompont(){
	$("#userSex").combobox({url:appPath+'/system/code_getCodesForComboxNoDefault.do?codeTypeId=1001',valueField:'id',textField:'text'});
	var allRoleUrl= appPath+"/system/role_pagedListAll.do";
	$.getJSON(allRoleUrl,function(data){//得到所有的角色信息
		var roleString="";
		var roles = data.rows;
		for(var i=0;roles&&i<roles.length;i++){
			var role = roles[i];
			var roleId = role.roleId;
			var roleName = role.roleName;
			var roleOrder =role.roleOrder;
			roleString+="<div class='checkClass'><input type='checkbox' value="+roleId+">"+roleName+"</div>";
		}
		$("#roleDiv").append($(roleString));
	});
}

function initJspGrid(){
	$("#userGrid").datagrid({
		url:appPath+'/system/user_pageList.do',
		height:'full',
		striped: true,
		fitColumns:true,
		queryParams: getQueryParam(),
		checkbox:true,
		frozenColumns:[[
		      {field:'ck',checkbox:true},
		      {field:'op',title:'操作',width:34,align:'center',formatter:fmtOp}
		        ]],
		columns:[[
		      {field:'userId',title:'登录帐号',width:100,align:'left',sortable:true},
		      {field:'userName',title:'用户姓名',width:80,align:'left',sortable:true},
		      {field:'userSexName',title:'性别',width:40,align:'center',sortable:true},
		      {field:'userMobile',title:'手机',width:100,align:'left',sortable:true},
		      {field:'userTel',title:'电话',width:100,align:'left',sortable:true},
		      {field:'userEmail',title:'邮件',width:200,align:'left',sortable:true},
		      {field:'userRemark',title:'备注',width:250,align:'left',sortable:true}
		      ]],
		 pagination:true,
		 rownumbers:true,
		 toolbar:[{
				id:'btnadd',
				text:'增加',
				iconCls:'icon-add',
				handler:function(){
					showAdd();
				}
			},{
				id:'btndel',
				text:'删除',
				iconCls:'icon-cancel',
				handler:function(){
					doDelete();
				}
			},'-',{
				id:'btnreset',
				text:'重置密码',
				iconCls:'icon-reset',
				handler:function(){
					doReset();
				}
			}]
	});
}

function doDelete(){
	var selections = $("#userGrid").datagrid('getSelections');
	if(selections == null || selections == ''){
		$.messager.alert('提示信息','请选择要删除的数据','info');
		return;
	}else{
		$.messager.confirm('提示信息','您确定要删除这些记录？',function(r){
			if(r){
				var ids = [];
				for(var i=0;i<selections.length;i++){
					ids.push(selections[i].userId);
				}
				$.ajax({
					url:appPath+'/system/user_delUser.do',
					data:{ids:ids.toString()},
					success:function(data){
						if(data!='ok'){
							$.messager.alert('提示信息','抱歉，删除未能完成，'+data,'error');
						}else{
							doQuery();
						}
					}
				});		
			}
		});
	}
}

/**
 * 密码重置
 * @param {} rowData
 */
function doReset(){
	var selections = $("#userGrid").datagrid('getSelections');
	if(selections == null || selections == ''){
		$.messager.alert('提示信息','请选择要重置密码的数据','info');
		return ;
	}else{
		$.messager.confirm('提示信息','您确定要重置这些用户的密码？<br/>请注意：重置后的密码与登录账号相同！',function(r){
			if(r){
				var ids = [];
				for(var i=0;i<selections.length;i++){
					ids.push(selections[i].userId);
				}
				$.ajax({
					url:appPath+'/system/user_resetPass.do',
					data:{ids:ids.toString()},
					type:"post",
					success:function(data){
						if(data!='ok'){
							$.messager.alert('提示信息','抱歉，密码重置未能完成 : '+data,'error');	
						}else{
							$.messager.alert('提示信息','密码重置成功！','info');
						}
					}
				});
			}
		});
	}
}

/**
 * 提交数据，包括增加，修改
 */
function doPostData(){
	if(!$('#addForm').form('validate')){
		return ;
	}
	var roleIds = []; 
	$("input[type='checkbox']:checked").each(function(i,t){
			var jq=$(this);
			var value = jq.attr("value");
			if(value&&value.length>0)roleIds.push(value);

	});
	if(roleIds.length<=0){
		$.messager.alert('提示信息','请选择用户角色!','info');
		return;
	}
	var type = $("#submitType").val();
	var typeStr = "";
	if(type == "save"){
		typeStr = "保存";
	}else if(type == "update"){
		typeStr = "更新";
	}
	
	var subData = $('#addForm');  
    var userinfo = subData.serialize();
    userinfo+="&roleIds="+roleIds;
	//用户信息维护
	$.ajax({
		url:appPath+'/system/user_'+type + '.do',
		type:"post",
		data:userinfo,
		success:function(data){
			if(data!='ok'){
				if(data == 'repeat'){
					$.messager.alert('提示信息','该登录帐号已存在，请重新输入！','info');
				}else{
					$.messager.alert('提示信息','抱歉，'+typeStr+'未能完成，'+data,'error');	
				}
			}else{
				doQuery();
				$('#addDlg').window('close');
			}
		}
	});
	
}

/**
 * 结束编辑（关闭对话框）
 */
function cancelPostData(){
	$('#addDlg').window('close');
	$("#name").show();
	$("#showNameSpan").html("");
}

/**
 * 获取请求信息
 */
function getQueryParam(){
	var queryObject = new Object();
	queryObject.userName = $('#queryUserName').val();
	return queryObject;
}

/**
 * 查询数据
 */
function doQuery(){
	$("#userGrid").datagrid('unselectAll');
	$("#userGrid").datagrid('load',getQueryParam());
}

/**
 * 展现编辑界面
 * @param {} rowData
 */
function showEdit(rowIndex){
	var rowData = $("#userGrid").datagrid("getRows")[rowIndex];
	$('#addForm').form('clear');
	$('#addForm').form('load',rowData);
	$("#submitType").val("update");
	$("#userId").attr("readonly","readonly");
	$("#userId").removeClass("inputText");
	$("#userId").addClass("readonlyText");
	$("#userSex").val(rowData.sex);
	showRoles(rowData.userId);
	$('#addDlg').window({
			title:'编辑用户',
			iconCls:'icon-edit',
			modal: true,
			shadow: true,
			collapsible:false,
			minimizable:false,
			maximizable:false
		});
	$("#notice").hide();
	$('#addDlg').window('move',{left:40,top:20});
	$('#addDlg').window('open');
}

function showAdd(){
	$('#addForm').form('clear');
	$('#submitType').val("save");
	$("#userId").removeAttr("readonly");
	$("#userId").removeClass("readonlyText");
	$("#userId").addClass("inputText");
	$("#userSex").combobox("setValue","");
	$('#addDlg').window({
				title:'增加用户',
				iconCls:'icon-add',
				modal: true,
				shadow: true,
				collapsible:false,
				minimizable:false,
				maximizable:false
			});
	$("#notice").show();
	$('#addDlg').window('move',{left:40,top:20});
	$('#addDlg').window('open');		
}

function showRoles(userId){
	if(!userId)return;
	var userRoleUrl = appPath+"/system/user_getUserRoles.do?userId="+userId;//得到用户角色信息
	$.getJSON(userRoleUrl,function(data){
		for(var m=0;data&&m<data.length;m++){
			$("input[type='checkbox']").each(function(i,t){
				var jq = $(this);
				var roleId = data[m].roleId;
				if(jq.attr("value")==roleId){
					jq.prop("checked",true);
				}
			});
		}
	});
}

function fmtOp(value,rowData,rowIndex){
	if(value=="footer")return;
	return "<a href='javascript:void(0)'><img width='12px' height='12px' style='border:0px' src='"+appPath+"/js/lib/jquery-easyui/themes/icons/pencil.png' title='编辑' onClick='showEdit("+rowIndex+")'/></a>";
}